﻿using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Releasers;
using Castle.Windsor;
using NUnit.Framework;

namespace WindsorInitConfig {
    [TestFixture]
    public class ChildContainerMemory {
        [Test]
        public void test() {
            using (var parentContainer = new WindsorContainer()) {
                parentContainer.Register(Component.For<Service1>().LifeStyle.Transient);
                for (var i = 0; i < 100000; i++) {
                    using (IWindsorContainer childContainer = new WindsorContainer()) {
                        //childContainer.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy();
                        parentContainer.AddChildContainer(childContainer);
                        var service1 = childContainer.Resolve<Service1>();
                        childContainer.Release(service1);
                        parentContainer.Release(service1);
                        if (i%100 == 0) {
                            GC.Collect(2);
                            Console.WriteLine("Iteration: {0}, Memory {1}", i, GC.GetTotalMemory(false));
                        }
                        parentContainer.RemoveChildContainer(childContainer);
                    }
                }
            }
        }

        [Test]
        public void testWithoutChildContainer() {
            using (var parentContainer = new WindsorContainer()) {
                parentContainer.Register(Component.For<Service1>().LifeStyle.Transient);
                for (var i = 0; i < 100000; i++) {
                    var service1 = parentContainer.Resolve<Service1>();
                    parentContainer.Release(service1);
                    if (i%100 == 0) {
                        GC.Collect(2);
                        Console.WriteLine("Iteration: {0}, Memory {1}", i, GC.GetTotalMemory(false));
                    }
                }
            }
        }

        public class Service1: IDisposable {
            private byte[] big = new byte[1000000];
            public void Dispose() {
            }
        }
    }
}